package com.nhvu.compoundword;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.support.v7.app.ActionBarActivity;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.nhvu.compoundword.base.CompoundWord;
import com.nhvu.compoundword.base.CompoundWordManager;
import com.nhvu.compoundword.library.Common;
import com.nhvu.compoundword.library.CommonMultil;
import com.nhvu.compoundword.library.MyGlobal;
import com.nhvu.compoundword.library.MyGlobal.Player;
import com.startapp.android.publish.StartAppSDK;

public class MultilPlayerActivity extends ActionBarActivity {
	List<String> listWord = new ArrayList<String>();
	List<Integer> listPoint = CommonMultil.getListPoint();
	List<CompoundWord> compoundWords;
	CompoundWordManager manager;
	ProgressBar progressBar;
	Button btnCellStart;
	Button btnCellEnd;
	int currentIndex = 0;
	int clickCounter = 0;
	int currentPointPlayerOne = 0;
	int currentPointPlayerTwo = 0;
	int countCorrect = 0;
	TextView tvwTimerPlayerOne;
	TextView tvwTimerPlayerTwo;
	TextView tvwTimerTotal;
	Boolean isPlayerOne;
	Boolean isPlayerTwo;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		// Init StartApp
		StartAppSDK.init(this, MyGlobal.StartApp.DEV_ID,
				MyGlobal.StartApp.APP_ID, true);
		// setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
		// Set full screen
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
				WindowManager.LayoutParams.FLAG_FULLSCREEN);
		setContentView(R.layout.activity_multil_player);
		// Timer player
		tvwTimerPlayerOne = (TextView) findViewById(R.id.tvwTimerPlayerOne);
		tvwTimerPlayerTwo = (TextView) findViewById(R.id.tvwTimerPlayerTwo);

		manager = new CompoundWordManager(this);
		initData();

		// Set text score
		int playerOneScore = CommonMultil
				.getPlayerScore(this, Player.PlayerOne);
		TextView tvwScorePlayerOne = (TextView) findViewById(R.id.tvwScorePlayerOne);
		tvwScorePlayerOne.setText(String.valueOf(playerOneScore));

		int playerTwoScore = CommonMultil
				.getPlayerScore(this, Player.PlayerTwo);
		TextView tvwScorePlayerTwo = (TextView) findViewById(R.id.tvwScorePlayerTwo);
		tvwScorePlayerTwo.setText(String.valueOf(playerTwoScore).toString());

		// Get player selection to display timer
		Intent intent = getIntent();
		String playerMode = intent
				.getStringExtra(MyGlobal.Params.SELECTED_PLAYER);
		displayTimerTotal();
		switch (playerMode) {
		case MyGlobal.PlayerSelection.PLAYER_ONE:
			isPlayerOne = true;
			displayTimerPlayerOne();
			break;
		case MyGlobal.PlayerSelection.PLAYER_TWO:
			isPlayerTwo = true;
			displayTimerPlayerTwo();
			break;
		case MyGlobal.PlayerSelection.THE_WINNER:
			String winner = CommonMultil.getCurrentWinner(this);
			if (winner.equals(MyGlobal.PlayerSelection.PLAYER_ONE))
				displayTimerPlayerOne();
			else
				displayTimerPlayerTwo();
			break;
		default:
			String winner1 = CommonMultil.getCurrentWinner(this);
			if (winner1.equals(MyGlobal.PlayerSelection.PLAYER_ONE))
				displayTimerPlayerTwo();
			else
				displayTimerPlayerOne();
			break;
		}
	}

	@Override
	public void onBackPressed() {
		Intent intent = new Intent(this, MainActivity.class);
		startActivity(intent);
		Common.closeApp(this);
	}

	/**
	 * Init list of words
	 */
	public void initData() {
		compoundWords = manager.getListImportantWordMultil();
		if (compoundWords == null
				|| compoundWords.size() < MyGlobal.MultilPlayerValues.TOTAL_WORD)
			compoundWords = manager.getListNoneImportantWordMultil();
		if (compoundWords == null
				|| compoundWords.size() < MyGlobal.MultilPlayerValues.TOTAL_WORD) {
			manager.updateUsedState(MyGlobal.TableName.MULTIL_PLAYER);
			compoundWords = manager.getListImportantWordMultil();
		}
		for (CompoundWord word : compoundWords) {
			String[] words = word.Words.split(" ");
			listWord.add(words[0]);
			listWord.add(words[1]);
		}
		Collections.shuffle(listWord);
		Collections.shuffle(listPoint);
		setData();
	}

	/**
	 * Set data
	 */
	public void setData() {
		ViewGroup groupFrame = (ViewGroup) findViewById(R.id.layoutFrame);
		for (int i = 0; i < groupFrame.getChildCount(); i++) {
			View childView = groupFrame.getChildAt(i);
			ViewGroup viewGroup = (ViewGroup) childView;
			setTextToButton(viewGroup);
		}
	}

	/**
	 * Set text to button
	 * 
	 * @param group
	 *            a ViewGroup
	 */
	public void setTextToButton(ViewGroup group) {
		for (int i = 0; i < group.getChildCount(); i++) {
			View childView = group.getChildAt(i);
			if (childView instanceof Button) {
				Button btnCell = (Button) childView;
				btnCell.setText(listWord.get(currentIndex).toString());
				switch (listPoint.get(currentIndex)) {
				case MyGlobal.MultilPlayerValues.KIND_POINT_ONE:
					btnCell.setBackgroundResource(R.drawable.bg_cell_10);
					btnCell.setTag(MyGlobal.MultilPlayerValues.KIND_POINT_ONE);
					break;
				case MyGlobal.MultilPlayerValues.KIND_POINT_TWO:
					btnCell.setBackgroundResource(R.drawable.bg_cell_20);
					btnCell.setTag(MyGlobal.MultilPlayerValues.KIND_POINT_TWO);
					break;
				case MyGlobal.MultilPlayerValues.KIND_POINT_THREE:
					btnCell.setBackgroundResource(R.drawable.bg_cell_30);
					btnCell.setTag(MyGlobal.MultilPlayerValues.KIND_POINT_THREE);
					break;
				default:
					btnCell.setBackgroundResource(R.drawable.bg_cell_50);
					btnCell.setTag(MyGlobal.MultilPlayerValues.KIND_POINT_FOUR);
					break;
				}
				currentIndex++;
			}
		}
	}

	/**
	 * Display timer player one
	 * 
	 */
	public void displayTimerPlayerOne() {
		int totalTime = MyGlobal.MultilPlayerValues.TIME_EACH_PLAYER;
		int downTime = MyGlobal.MultilPlayerValues.TIME_DOWN;
		// tvwTimerPlayerOne.setText(String.valueOf((totalTime / 1000)));
		isPlayerOne = true;
		isPlayerTwo = false;
		CommonMultil.setBackgroundTimer(tvwTimerPlayerTwo, tvwTimerPlayerOne);
		CountDownTimer myCountDownTimer = new CountDownTimer(totalTime,
				downTime) {
			@Override
			public void onTick(long millisUntilFinished) {
				tvwTimerPlayerOne.setText(String
						.valueOf((millisUntilFinished / 1000)));
			}

			@Override
			public void onFinish() {
				tvwTimerPlayerOne.setText("0");
				CommonMultil.setBackgroundTimer(tvwTimerPlayerOne,
						tvwTimerPlayerTwo);
				// Clear cells
				clearCell();
				displayTimerPlayerTwo();
			}
		};
		myCountDownTimer.start();
	}

	/**
	 * Display timer player two
	 * 
	 */
	public void displayTimerPlayerTwo() {
		int totalTime = MyGlobal.MultilPlayerValues.TIME_EACH_PLAYER;
		int downTime = MyGlobal.MultilPlayerValues.TIME_DOWN;
		// tvwTimerPlayerTwo.setText(String.valueOf((totalTime / 1000)));
		isPlayerTwo = true;
		isPlayerOne = false;
		CommonMultil.setBackgroundTimer(tvwTimerPlayerOne, tvwTimerPlayerTwo);
		CountDownTimer myCountDownTimer = new CountDownTimer(totalTime,
				downTime) {
			@Override
			public void onTick(long millisUntilFinished) {
				tvwTimerPlayerTwo.setText(String
						.valueOf((millisUntilFinished / 1000)));
			}

			@Override
			public void onFinish() {
				tvwTimerPlayerTwo.setText("0");
				CommonMultil.setBackgroundTimer(tvwTimerPlayerTwo,
						tvwTimerPlayerOne);
				// Clear cells
				clearCell();
				displayTimerPlayerOne();
			}
		};
		myCountDownTimer.start();
	}

	/**
	 * Display timer total
	 * 
	 */
	public void displayTimerTotal() {
		int totalTime = MyGlobal.MultilPlayerValues.TIME_TOTAL;
		int downTime = MyGlobal.MultilPlayerValues.TIME_DOWN;
		tvwTimerTotal = (TextView) findViewById(R.id.tvwTimerTotal);
		tvwTimerTotal.setText(String.valueOf((totalTime / 1000)));
		CountDownTimer myCountDownTimer = new CountDownTimer(totalTime,
				downTime) {
			@Override
			public void onTick(long millisUntilFinished) {
				tvwTimerTotal.setText(String
						.valueOf((millisUntilFinished / 1000)));
			}

			@Override
			public void onFinish() {
				finishMisson();
				finish();
				System.exit(0);
			}
		};
		myCountDownTimer.start();
	}

	/**
	 * Finish mission and move to result activity
	 * 
	 */
	public void finishMisson() {
		manager.updateUsedState(compoundWords, MyGlobal.TableName.MULTIL_PLAYER);
		Intent intent = new Intent(this, MultilPlayerResultActivity.class);
		intent.putExtra(MyGlobal.Params.PLAYER_ONE_POINT, currentPointPlayerOne);
		intent.putExtra(MyGlobal.Params.PLAYER_TWO_POINT, currentPointPlayerTwo);
		startActivity(intent);
	}

	/**
	 * Highlight cell and check meaning as player clicked
	 */
	public void hightLight(View view) {
		if (clickCounter == 0) {
			if (btnCellStart != null && btnCellEnd != null) {
				Common.setBackgroundOriginal(btnCellStart);
				Common.setBackgroundOriginal(btnCellEnd);
			}
			btnCellStart = (Button) view;
			if (isPlayerOne)
				CommonMultil.setBackgroundClickedPlayerOne(btnCellStart);
			else
				CommonMultil.setBackgroundClickedPlayerTwo(btnCellStart);
			clickCounter++;
			return;
		}
		if (clickCounter == 1) {
			clickCounter = 0;
			btnCellEnd = (Button) view;
			if (btnCellEnd == btnCellStart) {
				Common.setBackgroundOriginal(btnCellEnd);
				return;
			} else {
				if (isPlayerOne)
					CommonMultil.setBackgroundClickedPlayerOne(btnCellEnd);
				else
					CommonMultil.setBackgroundClickedPlayerTwo(btnCellEnd);
			}
		}
		// Check word exist
		String compoundWord = btnCellStart.getText().toString()
				+ btnCellEnd.getText().toString();
		Boolean isExist = manager.checkWordExistByWord(compoundWord);
		if (isExist) {
			countCorrect++;
			btnCellStart.setVisibility(View.INVISIBLE);
			btnCellEnd.setVisibility(View.INVISIBLE);
			int point = Common.getPoint(btnCellStart, btnCellEnd);
			if (isPlayerOne) {
				currentPointPlayerOne += point;
				TextView tvwPointPlayerOne = (TextView) findViewById(R.id.tvwPointPlayerOne);
				tvwPointPlayerOne
						.setText(String.valueOf(currentPointPlayerOne));
			} else {
				currentPointPlayerTwo += point;
				TextView tvwPointPlayerTwo = (TextView) findViewById(R.id.tvwPointPlayerTwo);
				tvwPointPlayerTwo
						.setText(String.valueOf(currentPointPlayerTwo));
			}
			showMessage("+" + point);
		} else {
			Common.setBackgroundWrong(btnCellStart);
			Common.setBackgroundWrong(btnCellEnd);
		}
	}

	/**
	 * Show message
	 */
	public void showMessage(String message) {
		final Toast toast = Toast.makeText(getApplicationContext(), message,
				Toast.LENGTH_SHORT);
		toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
		toast.show();
		Handler handler = new Handler();
		handler.postDelayed(new Runnable() {
			@Override
			public void run() {
				toast.cancel();
			}
		}, 1000);
	}

	/**
	 * Clear cell
	 * 
	 */
	public void clearCell() {
		Common.resetBackground(btnCellStart, btnCellEnd);
		btnCellEnd = null;
		btnCellStart = null;
		clickCounter = 0;
	}
}
